/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.proyectos.abstrac;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Rafael
 */
public abstract class  BeanAbstract<T>  {
   Class clase;
   @PersistenceContext(unitName="Proyectos2-ejbPU")
   private EntityManager entityManager;    
   @Resource
   SessionContext context;

    public BeanAbstract(Class clase) {
        this.clase = clase;
    }
   
   

    public EntityManager getEntityManager() {
        return entityManager;
    }


    public SessionContext getContext() {
        return context;
    }

   
   
   
   public void add(T entity) throws Exception 
   {
       try{
        entityManager.persist(entity);
       }catch(Exception e)
       {
           throw e;
       }
   }
   
 
   public void save(T entity) throws Exception
   {
       try{
           entityManager.merge(entity);
       }catch(Exception e)
       {
           throw e;
       }
   }
   
 
   public void delete(T entity) throws Exception
   {
       try{
           entityManager.remove(entity);
       }catch(Exception e)
       {
           throw e;
       }
   }
   
 
   public T get(BigDecimal id) throws Exception
   {
       try{
           return (T) entityManager.find(clase,id);
       }catch(Exception e)
       {
           throw e;
       }
   }    
   
   public List<T> query(String named,TreeMap vparametros)
   {
       Query que = this.entityManager.createNamedQuery(named);
       Set ordenes =vparametros.keySet();
       Iterator it = ordenes.iterator();
       while (it.hasNext())
       {
           String ckey = (String) it.next();
           que.setParameter(ckey,vparametros.get(ckey));
       }
       return que.getResultList();
   }
}
